/* eslint-disable no-loop-func */
/* eslint-disable no-use-before-define */
import { SetupContext, computed, defineComponent, ref, watch } from 'vue';
import FTreeView from '../../../tree-view/src/tree-view.component';
import { controlTreeViewProps, ControlTreeViewProps } from '../composition/props/control-tree-view.props';
import { cloneDeep } from 'lodash';
import { changeTreeNode } from '../composition/function/change-control-tree-node';

export default defineComponent({
    name: 'FControlTreeView',
    props: controlTreeViewProps,
    emits: ['outputValue', 'currentEvent'] as string[] | undefined,
    setup(props: ControlTreeViewProps, context: SetupContext) {
        // const data2 = ref(props.data2);
        /** 树表数据 */
        const domJsonComponents = ref(props.data);
        /** 树节点图标数据 */
        const treeNodeIconsData = ref(props.treeNodeIconsData);
        /** 树表是否支持可选状态 */
        const selectable = ref(props.selectable);
        /** 选中父节点会自动选中子节点 */
        const autoCheckChildren = ref(props.autoCheckChildren);
        /** 返回值展示父节点和子节点 */
        const cascade = ref(props.cascade);
        /** 是否显示图标集 */
        const showTreeNodeIcons = ref(props.showTreeNodeIcons);
        /** 是否显示连接线 */
        const showLines = ref(props.showLines);
        /** 新增值 */
        const newDataItem = ref(props.newDataItem);
        /** 连接线颜色 */
        const lineColor = ref(props.lineColor);
        /** 单元格高度 */
        const cellHeight = ref(props.cellHeight);

        const { changeControlTreeNode, onComponentClicked } = changeTreeNode(props, context);

        function onBuilderReady() {
            // componentInstanceList = designBuilder.instance.getAllComponents();
            // 更新控件json映射
            // domService.updateDomDgMap(componentInstanceList);
            // 重新挂载控件事件
            // reAttachComponentEvent(componentInstanceList);
        }

        function onBuilderReady() {
            // componentInstanceList = designBuilder.instance.getAllComponents();
            // 更新控件json映射
            // domService.updateDomDgMap(componentInstanceList);
            // 重新挂载控件事件
            // reAttachComponentEvent(componentInstanceList);
        }

        /** 处理数据 */
        function handleInputData(components: any, findComponents: any, number: number, parentId: string) {
            components.forEach((componentsItem: any) => {
                const findComponentsItem = {
                    oldId: componentsItem.id,
                    layer: number,
                    oldParent: parentId,
                    name: componentsItem.name || componentsItem.text || componentsItem.id,
                    type: componentsItem.type,
                    class: componentsItem.appearance?.class || ''
                };
                findComponents.push(cloneDeep(findComponentsItem));
                if (componentsItem.contents || componentsItem.buttons) {
                    handleInputData(componentsItem.contents || componentsItem.buttons, findComponents, number + 1, componentsItem.id);
                }
            });
            const findComponentsReverse = findComponents.reverse();
            return findComponentsReverse;
        }

        /** 按照treeview输入值排序 */
        function getSortedData(flatData: any) {
            const sortedData: any = [];
            const rootComponent = flatData.find((flatDataItem: any) => flatDataItem.layer === 0);
            flatData = flatData.filter((flatDataItem: any) => flatDataItem.layer !== 0);
            sortedData.push(rootComponent);
            let neededId = rootComponent.oldId;
            let back = 0;
            // 死循环时跳出
            let lock = 1000;
            while (flatData.length !== 0 || lock === 0) {
                const result = flatData.find((flatDataItem: any) => flatDataItem.oldParent === neededId);
                if (result) {
                    sortedData.push(result);
                    neededId = result.oldId;
                    flatData = flatData.filter((flatDataItem: any) => flatDataItem.oldId !== neededId);
                    back = 0;
                } else {
                    // 若非同层级，则找其父级的子
                    back -= 1;
                    neededId = sortedData.slice(back)[0].oldId;
                }
                lock -= 1;
            }
            return sortedData;
        }
        // id: '19',
        // avatar: 'check3',
        // code: '0001',
        // name: '生产部',
        // parent: '17',
        // layer: 2
        function formTreeViewFrame(originData: any) {
            originData.forEach((originDataItem: any, index: number) => {
                originDataItem.id = (index + 1).toString();
            });
            originData.forEach((originDataItem: any) => {
                originDataItem.parent = originData.find((item: any) => item.oldId === originDataItem.oldParent)?.id || '';
            });
            return originData;
        }
        /** 获取treeview所需数据 */
        function getTreeViewData() {
            let outputDataWithTreeViewFrame;
            if (domJsonComponents.value.length !== 0) {
                const components = [];
                components.push(domJsonComponents.value);
                const findComponents: any = [];
                const number = 0;
                const outputData = getSortedData(handleInputData(components, findComponents, number, ''));
                outputDataWithTreeViewFrame = formTreeViewFrame(outputData);
            }
            return outputDataWithTreeViewFrame;
        }
        function emitOutputValue(value: any) {
            context.emit('outputValue', value);
            const propertyId = value.data.displayText.data;
            const config = onComponentClicked(propertyId);
            // changeControlTreeNode(node);
        }

        function returnTreeView() {
            const treeViewData = getTreeViewData();
            return (
                <FTreeView
                    data={treeViewData}
                    treeNodeIconsData={treeNodeIconsData.value}
                    selectable={selectable.value}
                    autoCheckChildren={autoCheckChildren.value}
                    cascade={cascade.value}
                    showTreeNodeIcons={showTreeNodeIcons.value}
                    showLines={showLines.value}
                    newDataItem={newDataItem.value}
                    lineColor={lineColor.value}
                    cellHeight={cellHeight.value}
                    onOutputValue={(value: any) => emitOutputValue(value)}></FTreeView>
            );
        }
        return () => {
            return <>{returnTreeView()}</>;
        };
    }
});
